package top.ahwyy.controller.Action;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import top.ahwyy.controller.impl.cardImpl;
import top.ahwyy.controller.inter.card;
import top.ahwyy.model.carddata;
import top.ahwyy.utils.filterSpecialChar;

public class searchAction implements ServletRequestAware, ServletResponseAware {
	
	public HttpServletResponse response;
	public HttpServletRequest request;
	public String keyWords;
	
	public String execute(){
		response.setContentType("text/html;charset=utf-8");
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(keyWords == null || keyWords.equals(""))
			return null;
		card ci = new cardImpl();
		@SuppressWarnings("unchecked")
		ArrayList<Integer> forumIdLi = (ArrayList<Integer>) ci.searchCardByKeyWord(keyWords);
		System.out.println("size"+forumIdLi.size());
		String jsonStr = "[";
		if(forumIdLi.size() != 0){

			for(int i : forumIdLi){
				carddata cd = ci.getACarddataObjectByForumId(i);
				//System.out.println(cd.getTitle()+cd.getContent()+cd.getLastUpdate());
				String ct = filterSpecialChar.filterSpecialChar2(cd.getContent());
				if(ct.length()>90)
					ct = ct.substring(0,90)+"...";
				jsonStr+="{\"title\":\""+filterSpecialChar.filterSpecialChar2(cd.getTitle())+"\",\"content\":\""+ct+"\",\"lastUpdate\":\""+cd.getLastUpdate()+"\",\"forumId\":\""+cd.getForumId()+"\"},";
			}
		}
		
		jsonStr = jsonStr.substring(0, jsonStr.length()-1);
		jsonStr+="]";
		System.out.println("jsonStr"+jsonStr);
		PrintWriter pw = null;
		try {
			pw = response.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		pw.print(jsonStr);
		
		
		return null;
	}
	
	@Override
	public void setServletResponse(HttpServletResponse arg0) {
		// TODO Auto-generated method stub
		this.response = arg0;
	}

	@Override
	public void setServletRequest(HttpServletRequest arg0) {
		// TODO Auto-generated method stub
		this.request = arg0;
	}

}
